package handler

import (
	"encoding/json"
	"net/http"
	"url-shortener/internal/service"
	"url-shortener/internal/util"
)

type Handler struct {
	service *service.Service
	baseURL string
}

func NewHandler(service *service.Service, baseURL string) *Handler {
	return &Handler{
		service: service,
		baseURL: baseURL,
	}
}

type ShortenRequest struct {
	URL string `json:"url"`
}

type ShortenResponse struct {
	ShortURL string `json:"short_url"`
}

// HandleShorten 处理URL缩短请求
func (h *Handler) HandleShorten(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req ShortenRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request body", http.StatusBadRequest)
		return
	}

	if req.URL == "" {
		http.Error(w, "URL is required", http.StatusBadRequest)
		return
	}

	// 规范化URL
	longURL := util.SanitizeURL(req.URL)

	// 调用服务生成短码
	shortCode, err := h.service.ShortenURL(longURL)
	if err != nil {
		http.Error(w, "Failed to shorten URL", http.StatusInternalServerError)
		return
	}

	// 构建响应
	resp := ShortenResponse{
		ShortURL: h.baseURL + "/" + shortCode,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(resp)
}

// HandleRedirect 处理短链重定向
func (h *Handler) HandleRedirect(w http.ResponseWriter, r *http.Request) {
	shortCode := r.URL.Path[1:] // 去掉开头的"/"
	if shortCode == "" {
		http.NotFound(w, r)
		return
	}

	// 获取原始URL
	longURL, err := h.service.GetOriginalURL(shortCode)
	if err != nil {
		http.NotFound(w, r)
		return
	}

	// 重定向到原始URL
	http.Redirect(w, r, longURL, http.StatusFound)
}